"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Plus, Search, Edit, Trash2, MoreHorizontal, Key } from "lucide-react"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"

// 模拟权限数据
const mockPermissions = [
  {
    id: 1,
    name: "查看用户",
    code: "user:read",
    module: "用户管理",
    description: "允许查看用户列表和用户详细信息",
    type: "read",
    status: "active",
    createdAt: "2024-01-15",
    roles: ["超级管理员", "管理员"],
  },
  {
    id: 2,
    name: "编辑用户",
    code: "user:write",
    module: "用户管理",
    description: "允许创建、编辑和删除用户",
    type: "write",
    status: "active",
    createdAt: "2024-01-15",
    roles: ["超级管理员", "管理员"],
  },
  {
    id: 3,
    name: "查看角色",
    code: "role:read",
    module: "角色管理",
    description: "允许查看角色列表和角色详细信息",
    type: "read",
    status: "active",
    createdAt: "2024-01-16",
    roles: ["超级管理员", "管理员"],
  },
  {
    id: 4,
    name: "编辑角色",
    code: "role:write",
    module: "角色管理",
    description: "允许创建、编辑和删除角色",
    type: "write",
    status: "active",
    createdAt: "2024-01-16",
    roles: ["超级管理员"],
  },
  {
    id: 5,
    name: "查看权限",
    code: "permission:read",
    module: "权限管理",
    description: "允许查看权限列表和权限详细信息",
    type: "read",
    status: "active",
    createdAt: "2024-01-17",
    roles: ["超级管理员", "管理员"],
  },
  {
    id: 6,
    name: "编辑权限",
    code: "permission:write",
    module: "权限管理",
    description: "允许创建、编辑和删除权限",
    type: "write",
    status: "active",
    createdAt: "2024-01-17",
    roles: ["超级管理员"],
  },
  {
    id: 7,
    name: "查看菜单",
    code: "menu:read",
    module: "菜单管理",
    description: "允许查看菜单列表和菜单详细信息",
    type: "read",
    status: "active",
    createdAt: "2024-01-18",
    roles: ["超级管理员", "管理员"],
  },
  {
    id: 8,
    name: "编辑菜单",
    code: "menu:write",
    module: "菜单管理",
    description: "允许创建、编辑和删除菜单",
    type: "write",
    status: "active",
    createdAt: "2024-01-18",
    roles: ["超级管理员"],
  },
]

const modules = ["用户管理", "角色管理", "权限管理", "菜单管理", "系统设置", "统计报表"]
const permissionTypes = ["read", "write", "delete", "execute"]

// 模拟权限分组数据
const permissionGroups = [
  {
    module: "用户管理",
    permissions: mockPermissions.filter((p) => p.module === "用户管理"),
    icon: "👥",
    color: "bg-blue-100 text-blue-800",
  },
  {
    module: "角色管理",
    permissions: mockPermissions.filter((p) => p.module === "角色管理"),
    icon: "🛡️",
    color: "bg-green-100 text-green-800",
  },
  {
    module: "权限管理",
    permissions: mockPermissions.filter((p) => p.module === "权限管理"),
    icon: "🔑",
    color: "bg-purple-100 text-purple-800",
  },
  {
    module: "菜单管理",
    permissions: mockPermissions.filter((p) => p.module === "菜单管理"),
    icon: "📋",
    color: "bg-orange-100 text-orange-800",
  },
]

export default function PermissionsPage() {
  const [permissions, setPermissions] = useState(mockPermissions)
  const [searchTerm, setSearchTerm] = useState("")
  const [selectedModule, setSelectedModule] = useState("all")
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
  const [selectedPermission, setSelectedPermission] = useState<any>(null)
  const [newPermission, setNewPermission] = useState({
    name: "",
    code: "",
    module: "",
    description: "",
    type: "",
  })

  const filteredPermissions = permissions.filter((permission) => {
    const matchesSearch =
      permission.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      permission.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
      permission.description.toLowerCase().includes(searchTerm.toLowerCase())

    const matchesModule = selectedModule === "all" || permission.module === selectedModule

    return matchesSearch && matchesModule
  })

  const handleAddPermission = () => {
    const permission = {
      id: permissions.length + 1,
      ...newPermission,
      status: "active",
      createdAt: new Date().toISOString().split("T")[0],
      roles: [],
    }
    setPermissions([...permissions, permission])
    setNewPermission({ name: "", code: "", module: "", description: "", type: "" })
    setIsAddDialogOpen(false)
  }

  const handleEditPermission = () => {
    setPermissions(
      permissions.map((permission) =>
        permission.id === selectedPermission.id ? { ...permission, ...selectedPermission } : permission,
      ),
    )
    setIsEditDialogOpen(false)
    setSelectedPermission(null)
  }

  const handleDeletePermission = (id: number) => {
    setPermissions(permissions.filter((permission) => permission.id !== id))
  }

  const getStatusBadge = (status: string) => {
    return status === "active" ? (
      <Badge variant="default" className="bg-foreground text-background">
        启用
      </Badge>
    ) : (
      <Badge variant="secondary" className="bg-gray-100 text-gray-800">
        禁用
      </Badge>
    )
  }

  const getTypeBadge = (type: string) => {
    const colors = {
      read: "bg-blue-100 text-blue-800",
      write: "bg-orange-100 text-orange-800",
      delete: "bg-red-100 text-red-800",
      execute: "bg-purple-100 text-purple-800",
    }
    return (
      <Badge variant="outline" className={colors[type as keyof typeof colors] || "bg-gray-100 text-gray-800"}>
        {type}
      </Badge>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-bold tracking-tight">权限管理</h2>
          <p className="text-muted-foreground">管理系统权限节点和访问控制</p>
        </div>
        <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="mr-2 h-4 w-4" />
              添加权限
            </Button>
          </DialogTrigger>
          <DialogContent className="sm:max-w-[500px]">
            <DialogHeader>
              <DialogTitle>添加新权限</DialogTitle>
              <DialogDescription>创建一个新的系统权限节点</DialogDescription>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="name" className="text-right">
                  权限名称
                </Label>
                <Input
                  id="name"
                  value={newPermission.name}
                  onChange={(e) => setNewPermission({ ...newPermission, name: e.target.value })}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="code" className="text-right">
                  权限代码
                </Label>
                <Input
                  id="code"
                  value={newPermission.code}
                  onChange={(e) => setNewPermission({ ...newPermission, code: e.target.value })}
                  className="col-span-3"
                  placeholder="例如: user:read"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="module" className="text-right">
                  所属模块
                </Label>
                <Select
                  value={newPermission.module}
                  onValueChange={(value) => setNewPermission({ ...newPermission, module: value })}
                >
                  <SelectTrigger className="col-span-3">
                    <SelectValue placeholder="选择模块" />
                  </SelectTrigger>
                  <SelectContent>
                    {modules.map((module) => (
                      <SelectItem key={module} value={module}>
                        {module}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="type" className="text-right">
                  权限类型
                </Label>
                <Select
                  value={newPermission.type}
                  onValueChange={(value) => setNewPermission({ ...newPermission, type: value })}
                >
                  <SelectTrigger className="col-span-3">
                    <SelectValue placeholder="选择类型" />
                  </SelectTrigger>
                  <SelectContent>
                    {permissionTypes.map((type) => (
                      <SelectItem key={type} value={type}>
                        {type}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="description" className="text-right">
                  描述
                </Label>
                <Textarea
                  id="description"
                  value={newPermission.description}
                  onChange={(e) => setNewPermission({ ...newPermission, description: e.target.value })}
                  className="col-span-3"
                />
              </div>
            </div>
            <DialogFooter>
              <Button type="submit" onClick={handleAddPermission}>
                创建权限
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      <Tabs defaultValue="list" className="space-y-4">
        <TabsList>
          <TabsTrigger value="list">权限列表</TabsTrigger>
          <TabsTrigger value="groups">权限分组</TabsTrigger>
        </TabsList>

        <TabsContent value="list" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>权限列表</CardTitle>
              <CardDescription>系统中所有权限节点的详细信息</CardDescription>
              <div className="flex items-center space-x-2">
                <div className="relative flex-1 max-w-sm">
                  <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="搜索权限..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-8"
                  />
                </div>
                <Select value={selectedModule} onValueChange={setSelectedModule}>
                  <SelectTrigger className="w-40">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">所有模块</SelectItem>
                    {modules.map((module) => (
                      <SelectItem key={module} value={module}>
                        {module}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>权限名称</TableHead>
                    <TableHead>权限代码</TableHead>
                    <TableHead>所属模块</TableHead>
                    <TableHead>类型</TableHead>
                    <TableHead>描述</TableHead>
                    <TableHead>关联角色</TableHead>
                    <TableHead>状态</TableHead>
                    <TableHead className="text-right">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredPermissions.map((permission) => (
                    <TableRow key={permission.id}>
                      <TableCell className="font-medium">
                        <div className="flex items-center">
                          <Key className="mr-2 h-4 w-4 text-primary" />
                          {permission.name}
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline">{permission.code}</Badge>
                      </TableCell>
                      <TableCell>
                        <Badge variant="secondary">{permission.module}</Badge>
                      </TableCell>
                      <TableCell>{getTypeBadge(permission.type)}</TableCell>
                      <TableCell className="max-w-xs truncate">{permission.description}</TableCell>
                      <TableCell>
                        <div className="flex flex-wrap gap-1">
                          {permission.roles.slice(0, 2).map((role) => (
                            <Badge key={role} variant="outline" className="text-xs">
                              {role}
                            </Badge>
                          ))}
                          {permission.roles.length > 2 && (
                            <Badge variant="outline" className="text-xs">
                              +{permission.roles.length - 2}
                            </Badge>
                          )}
                        </div>
                      </TableCell>
                      <TableCell>{getStatusBadge(permission.status)}</TableCell>
                      <TableCell className="text-right">
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button variant="ghost" className="h-8 w-8 p-0">
                              <span className="sr-only">打开菜单</span>
                              <MoreHorizontal className="h-4 w-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuItem
                              onClick={() => {
                                setSelectedPermission(permission)
                                setIsEditDialogOpen(true)
                              }}
                            >
                              <Edit className="mr-2 h-4 w-4" />
                              编辑
                            </DropdownMenuItem>
                            <DropdownMenuItem
                              onClick={() => handleDeletePermission(permission.id)}
                              className="text-destructive"
                            >
                              <Trash2 className="mr-2 h-4 w-4" />
                              删除
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="groups" className="space-y-4">
          <div className="grid gap-4 md:grid-cols-2">
            {permissionGroups.map((group) => (
              <Card key={group.module}>
                <CardHeader>
                  <CardTitle className="flex items-center">
                    <span className="mr-2 text-lg">{group.icon}</span>
                    {group.module}
                  </CardTitle>
                  <CardDescription>{group.permissions.length} 个权限节点</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2">
                    {group.permissions.map((permission) => (
                      <div key={permission.id} className="flex items-center justify-between p-2 rounded-lg border">
                        <div className="flex items-center space-x-2">
                          <Key className="h-4 w-4 text-muted-foreground" />
                          <span className="text-sm font-medium">{permission.name}</span>
                          {getTypeBadge(permission.type)}
                        </div>
                        <div className="flex items-center space-x-1">
                          {permission.roles.slice(0, 2).map((role) => (
                            <Badge key={role} variant="outline" className="text-xs">
                              {role}
                            </Badge>
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>
      </Tabs>

      {/* 编辑权限对话框 */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>编辑权限</DialogTitle>
            <DialogDescription>修改权限信息和配置</DialogDescription>
          </DialogHeader>
          {selectedPermission && (
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-name" className="text-right">
                  权限名称
                </Label>
                <Input
                  id="edit-name"
                  value={selectedPermission.name}
                  onChange={(e) => setSelectedPermission({ ...selectedPermission, name: e.target.value })}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-code" className="text-right">
                  权限代码
                </Label>
                <Input
                  id="edit-code"
                  value={selectedPermission.code}
                  onChange={(e) => setSelectedPermission({ ...selectedPermission, code: e.target.value })}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-module" className="text-right">
                  所属模块
                </Label>
                <Select
                  value={selectedPermission.module}
                  onValueChange={(value) => setSelectedPermission({ ...selectedPermission, module: value })}
                >
                  <SelectTrigger className="col-span-3">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {modules.map((module) => (
                      <SelectItem key={module} value={module}>
                        {module}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-type" className="text-right">
                  权限类型
                </Label>
                <Select
                  value={selectedPermission.type}
                  onValueChange={(value) => setSelectedPermission({ ...selectedPermission, type: value })}
                >
                  <SelectTrigger className="col-span-3">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {permissionTypes.map((type) => (
                      <SelectItem key={type} value={type}>
                        {type}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-description" className="text-right">
                  描述
                </Label>
                <Textarea
                  id="edit-description"
                  value={selectedPermission.description}
                  onChange={(e) => setSelectedPermission({ ...selectedPermission, description: e.target.value })}
                  className="col-span-3"
                />
              </div>
            </div>
          )}
          <DialogFooter>
            <Button type="submit" onClick={handleEditPermission}>
              保存更改
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
